<!--
 * @Author: LAB
 * @Date: 2021-01-27 23:13:35
 * @Description: 上传图片
 * @FilePath: \file-tools\upload-img\upload-img-base.vue
-->
<template>
  <div class="upload-img" v-if="maxLength > 0">
    <input type="file" @change="getImg" :multiple="maxLength > 1" />
    <i class="el-icon-plus"></i>
  </div>
</template>

<script>
export default {
  props: {
    maxLength: {
      type: Number,
      default: 2
    },
    // 初始化后的uploadTools
    fileTools: {
      type: Object,
      default: function () {
        return null
      }
    }
  },
  methods: {
    async getImg(event) {
      let files = event.target.files;
      let fileLength = files.length;
      const defaultImg = require("./loading.svg")
      fileLength = files.length > this.maxLength ? this.maxLength : files.length;
      let uploadImgList = Array.apply(null, Array(fileLength)).map(() => defaultImg)
      this.$emit("getImg", uploadImgList);
      for (let i = 0; i < fileLength; i++) {
        let file = files[i];
        try {
          let fileTools = this.fileTools || this.$fileTools
          let minfile = await fileTools.compressImg(file)
          let url = await fileTools.uploadFile(minfile)
          uploadImgList[i] = url
          this.$emit("getImg", uploadImgList);
        } catch (error) {
          this.$emit("getImg", uploadImgList);
        }
      }
      let finalImgList = []
      for (const key in uploadImgList) {
        if (Object.hasOwnProperty.call(uploadImgList, key)) {
          const element = uploadImgList[key];
          if (element != defaultImg) {
            finalImgList.push(element)
          }
        }
      }
      this.$emit("getImg", finalImgList);
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-img {
  width: 120px;
  height: 120px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  cursor: pointer;
  line-height: 146px;
  vertical-align: top;
  overflow: hidden;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  > input {
    position: absolute;
    opacity: 0;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
  }
}
</style>